package www.houdoudou.com.supplier;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import www.houdoudou.com.common.CommonFileFunction;
import www.houdoudou.com.common.CommonFunction;
import www.houdoudou.com.common.CommonMathFunction;

public class ProductManagement {

	
	
	public static	JSONObject  manageProduct(String jsonData){
		JSONObject result = new JSONObject();
		JSONObject jsonfrom= JSONObject.fromObject(jsonData);				
		//判断请求的功能
		int FunctionCode=jsonfrom.getInt("FunctionCode");
		   PreparedStatement pstm=null; 
		   Statement  stm=null;
		   ResultSet rs=null; 		 
		   ///注意
		   String CurrentConnUser=CommonMathFunction.genRandomNum(10);
		   Connection conn= CommonFunction. getCurrentConnection();
		   if(CommonFunction.ConnUser.isEmpty()){ CommonFunction.ConnUser=CurrentConnUser; }
		   
		   // 此值代表用户身份，不同的身份，对于同一个增删改查函数，有不同的处理，防止出错。
		   int Manager_Authority= jsonfrom.getInt("Manager_Authority");
		   switch(FunctionCode){
		   
		// 查询 
			case 1:{
				try {
					   int Product_ID=jsonfrom.getInt("Product_ID");
					
					   String sql = "select * from Tb_Product where Product_ID="+Product_ID+"";    
						stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
						rs= stm.executeQuery(sql);
						
						if(rs.next()){	
				            boolean isAuthorityEnough=false;
				            if(Manager_Authority<4) isAuthorityEnough=true;
                            if(Manager_Authority==4) {
                            	if(jsonfrom.getString("Owner_Telnum").equals(rs.getString("Owner_Telnum"))){
                            		isAuthorityEnough=true;
                            	}else{
                            		result.put("ActionStatus", false);
									result.put("ErrorInfo", "无权查询该目录");
                            	}
                            }
                            if(Manager_Authority==5) {
                            	if(jsonfrom.getString("Supplier_Telnum").equals(rs.getString("Supplier_Telnum"))){
                            		isAuthorityEnough=true;
                            	}else{
                            		result.put("ActionStatus", false);
									result.put("ErrorInfo", "无权查询该目录");
                            	}
                            }
                     
                            if(isAuthorityEnough){
							result.put("ActionStatus", true);
							result.put("ErrorInfo", "查询成功");						
							result.put("Product_Name", rs.getString("Product_Name"));
							result.put("Product_isAuthority", rs.getString("Product_isAuthority"));
							result.put("Product_Detail", rs.getString("Product_Detail"));
							result.put("Product_Update_No", rs.getInt("Product_Update_No"));
							result.put("Index_ID", rs.getInt("Index_ID"));
							result.put("Product_Sale_No", rs.getInt("Product_Sale_No"));
							result.put("Product_PicDir", rs.getString("Product_PicDir"));
							// 新增参数。调用BranchManagement, 查询所有	
						      jsonfrom.put("BranchFunctionCode", 5);
						     JSONObject branchManagecheck=BranchManagement.manage(jsonfrom.toString());
							  if( !branchManagecheck.getBoolean("ActionStatus")){
								   result= branchManagecheck;
								    break;}else{
								    	 result.put("Branches", branchManagecheck.getJSONArray("Branches")); 
								    }
							
                            }
						
							
						
					}else{
						result.put("ActionStatus", false);
						result.put("ErrorInfo", "要查询的目录不存在");
					}
						
						
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result.put("ActionStatus", false);
					result.put("ErrorInfo", "数据库查询异常");
				}
				
				break;}//case1
			
			//修改 按身份进行了区别。
			case 2:{
				 
				   try {
					   int Product_ID=jsonfrom.getInt("Product_ID");
						 String Supplier_Telnum=jsonfrom.getString("Supplier_Telnum");
					   String sql = "select * from Tb_Product where Product_ID="+Product_ID+" and Supplier_Telnum="+Supplier_Telnum+"";    
						stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
						rs= stm.executeQuery(sql);
					if(rs.next()){		
							 Manager_Authority=jsonfrom.getInt("Manager_Authority");
							switch(Manager_Authority){
						
							case 5:{						
								rs.updateString("Product_Name", jsonfrom.getString("Product_Name"));
								rs.updateString("Product_isAuthority", jsonfrom.getString("Product_isAuthority"));
								rs.updateString("Product_Detail", jsonfrom.getString("Product_Detail"));
								
								rs.updateInt("Index_ID", jsonfrom.getInt("Index_ID"));
								rs.updateInt("Product_Update_No", rs.getInt("Product_Update_No")+1);
								rs.updateRow();
								result.put("ActionStatus", true);
								result.put("ErrorInfo", "更新成功");
								// 新增参数。调用BranchManagement, 删除旧记录						
								jsonfrom.put("BranchFunctionCode", 3);
								JSONObject branchManagecheck=BranchManagement.manage(jsonfrom.toString());
								      if( !branchManagecheck.getBoolean("ActionStatus")){
									   result= branchManagecheck;
								       break;}
								   // 新增参数。调用BranchManagement, 添加新记录	
								      jsonfrom.put("BranchFunctionCode", 4);
								      branchManagecheck=BranchManagement.manage(jsonfrom.toString());
									  if( !branchManagecheck.getBoolean("ActionStatus")){
										   result= branchManagecheck;
										    break;}
							   
							
							                break;}
							
						  default:{
							  result.put("ActionStatus", false);
								result.put("ErrorInfo", "无权修改");
						           break;    }
							
							
							}// end of switch(Manager_Authority)																																						
					
						}else{
							result.put("ActionStatus", false);
							result.put("ErrorInfo", "要修改的目录不存在");
						}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result.put("ActionStatus", false);
					result.put("ErrorInfo", "数据库查询异常");
				}
				
			break;} //case 2
			
			case 3:{
			     
							if(Manager_Authority==5){
								
								 String Supplier_Telnum=jsonfrom.getString("Supplier_Telnum");
								 JSONArray Products= jsonfrom.getJSONArray("Products");
								 for(int i=0;i<Products.size();i++){
								 try{						
									
									 int  Product_ID=Products.getJSONObject(i).getInt("Product_ID");
									 /*---------删图片  必须先查询后删除--------*/    
										JSONObject jsonInner1=jsonfrom;      
										   jsonInner1.put("FunctionCode", 1);
										   jsonInner1.put("Product_ID",  Product_ID);
										   System.out.println("----delet jsonInner1_-----"+jsonInner1.toString());
										   JSONObject jsonInner1_back= ProductManagement.manageProduct(jsonInner1.toString()); 
										   System.out.println("----delet jsonInner1_back-----"+jsonInner1_back.toString());
										      String Product_PicDir=jsonInner1_back.getString("Product_PicDir");
										      CommonFileFunction.deletePic(Product_PicDir);
								  
									 String	sql	=" delete from  Tb_Product where Product_ID="+Product_ID+" and Supplier_Telnum="+Supplier_Telnum+"";									   
									             stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);  							           
									            		 stm.executeUpdate(sql);  	
									     				
															result.put("ActionStatus", true);
															result.put("ErrorInfo", "删除成功");
															// 调用BranchManagement, 删除旧记录						
															jsonfrom.put("BranchFunctionCode", 3);
															jsonfrom.put("Product_ID", Product_ID);
															JSONObject branchManagecheck=BranchManagement.manage(jsonfrom.toString());
															      if( !branchManagecheck.getBoolean("ActionStatus")){
																   result= branchManagecheck;
															       break;}
															
												} catch (SQLException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
													result.put("ActionStatus", false);
													result.put("ErrorInfo", "数据库删除操作失败");
												    break;
												} 							
										
								 }// end of for	
									
						}else{
							result.put("ActionStatus", false);
							result.put("ErrorInfo", "无权操作");}
						
				
				
			break;}
			
			
			// 新增  思路，先添加Tb_Product, 获取Product_ID,写入原来的json,再写BranchFunctionCode=4，用于原来json中的子配和新生产的Product_ID共同用于添加。
			case 4:{
				 if(Manager_Authority==5){
				
					 try{
										
						  String sql = "insert  into Tb_Product (Product_Name,Supplier_Telnum,Product_isAuthority,Product_Detail,Product_Update_No,Index_ID,Owner_Telnum,Product_PicDir,Product_Sale_No) values (?,?,?,?,?,?,?,?,?)";
			              	pstm=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
							pstm.setString(1, jsonfrom.getString("Product_Name"));
							pstm.setString(2, jsonfrom.getString("Supplier_Telnum"));
							pstm.setString(3, jsonfrom.getString("Product_isAuthority"));
							pstm.setString(4, jsonfrom.getString("Product_Detail"));
							pstm.setInt(5, 1);
							pstm.setInt(6, jsonfrom.getInt("Index_ID"));
							pstm.setString(7, jsonfrom.getString("Owner_Telnum"));
							pstm.setString(8, "image");
							pstm.setInt(9, 0);			
						    pstm.executeUpdate();
						   
							rs=pstm.getGeneratedKeys();
							if(rs.next()){
								int Product_ID= rs.getInt(1);
							result.put("Product_ID",Product_ID);
							/*---------构造图片的下载上传地址,返回给商家端，商家端根据下载地址,上传图片到该地址,暂不考虑IP变动------------*/
							String Product_PicDir="";
							String PicBaseAddress=CommonFileFunction.getPicBaseAddress();
							Product_PicDir=PicBaseAddress+jsonfrom.getString("Owner_Telnum")+"/"+jsonfrom.getString("Supplier_Telnum")+"/"+rs.getInt(1)+"."+jsonfrom.getString("picType");
							result.put("Product_PicDir",Product_PicDir);
							/*---------复写图片地址------------*/
							if(modifyPic_Dir(Product_ID, Product_PicDir)){
								 result.put("ActionStatus", true);
									result.put("ErrorInfo", "增加成功");
							}else{
								result.put("ActionStatus", false);
								result.put("ErrorInfo", "图片地址处理失败");
							}
							// 新增参数。调用BranchManagement,
							jsonfrom.put("Product_ID", Product_ID);
							jsonfrom.put("BranchFunctionCode", 4);
							JSONObject branchManagecheck=BranchManagement.manage(jsonfrom.toString());
							      if( !branchManagecheck.getBoolean("ActionStatus")){
								   result= branchManagecheck;
							       }else{
							    	   result.put("Branches", branchManagecheck.getJSONArray("Branches")); 
							       }
							}else{
								 result.put("ActionStatus", false);
									result.put("ErrorInfo", "获取自增产品编号失败");
							}
							
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							result.put("ActionStatus", false);
							result.put("ErrorInfo", "数据库异常");
						}
						 }// end of if manager_authority==3
						 else{
							 result.put("ActionStatus", false);
								result.put("ErrorInfo", "无权操作");}			
			   break;}// case 4	  
			
			
			//查询所有 必须带着供应商的参数来查，不然没有意义
			 case 5:{
				  try {
					  
					  
					  String Supplier_Telnum=jsonfrom.getString("Supplier_Telnum");	 
					  String sql = null;
					  int Query_Way = 0;
					  // 要添加 按时间标签，温度标签来查询下，但是为了不影响原来的使用，不能随便加	Query_Way,这里用Manager_Authority来判断，是顾客才要求获取 Query_Way.
					  //暂时不想改 供应商查询目录的android代码，这里写得有点乱，
					  // 以后这两个 if(Manager_Authority==)要用 swich Query_Way代替
					  if(Manager_Authority==6){
						  Query_Way=jsonfrom.getInt("Query_Way");
						switch(Query_Way){
						case 2:{   
							       int Index_ID=jsonfrom.getInt("Index_ID");
						           sql = "select * from  Tb_Product where Supplier_Telnum="+Supplier_Telnum+" and Index_ID="+Index_ID+" and Product_isAuthority="+"1"; 
						                   break;}				
						   }  
					  }
					 
					  // 以下这一条，要用 Query_Way=1来代替
					  if(Manager_Authority==5){
						  sql = "select * from  Tb_Product where Supplier_Telnum="+Supplier_Telnum+"";  
						  Query_Way=1;}
					   
						stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
						rs= stm.executeQuery(sql);
						JSONArray Products= new JSONArray();
						while(rs.next()){
							JSONObject product= new JSONObject();
							boolean isadd=false;
						switch(Manager_Authority){							            
						case 5:{					
								isadd=true;
							        break;}	
			            
						case 6:{					
							isadd=true;
						        break;}	
		              }
						if(isadd){
							
							int Product_ID=rs.getInt("Product_ID");
							product.put("Product_ID",  Product_ID);
							product.put("Product_Name", rs.getString("Product_Name"));
							product.put("Product_isAuthority", rs.getString("Product_isAuthority"));
							product.put("Product_Detail", rs.getString("Product_Detail"));
							product.put("Product_Update_No", rs.getInt("Product_Update_No"));
							product.put("Product_Sale_No", rs.getInt("Product_Sale_No"));
							product.put("Supplier_Telnum", rs.getString("Supplier_Telnum"));
							product.put("Product_PicDir", rs.getString("Product_PicDir"));
							
							/*-----------获取目录名字-----------*/
						
							jsonfrom.put("FunctionCode", 1);
							jsonfrom.put("Index_ID", rs.getInt("Index_ID"));	
							JSONObject indexNameQuery= IndexManagement.managerIndex(jsonfrom.toString());						
							product.put("Index_Name", indexNameQuery.getString("Index_Name"));
							
							/*-----------获取自配置-----------*/
							
							jsonfrom.put("BranchFunctionCode", 5);
							 jsonfrom.put("Query_Way",Query_Way);
							jsonfrom.put("Product_ID", Product_ID);	
							JSONObject BranchesQuery= BranchManagement.manage(jsonfrom.toString());						
							product.put("Branches", BranchesQuery.getJSONArray("Branches"));
							
							
							Products.add(product);               
						                         }
						
						}
						result.put("ActionStatus", true);
						result.put("ErrorInfo", "成功");
						result.put("Products",Products);
				   
				  }catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						result.put("ActionStatus", false);
						result.put("ErrorInfo", "查询失败");
					} 
						
						
					 break;  } //case5
			
			
			
			
			
		   } // end of switch functionCode
		   
		
		   
		   if(CommonFunction.ConnUser.equals(CurrentConnUser)){
			   CommonFunction.ConnUser="";  }
		   CommonFunction.closeConn(conn, pstm, stm, rs);
			  return result;
	}
	
	
	   public static boolean modifyPic_Dir(int Product_ID,String Product_PicDir){
		   boolean result=true;
		   PreparedStatement pstm=null; 
		   Statement  stm=null;
		   ResultSet rs=null; 		 
		   Connection conn= CommonFunction. getCurrentConnection();
		 
			 try{
		   String sql = "select * from Tb_Product where Product_ID="+Product_ID+"";    
			stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
			rs= stm.executeQuery(sql);
		if(rs.next()){		
								
					rs.updateString("Product_PicDir", Product_PicDir);
				
					rs.updateInt("Product_Update_No", rs.getInt("Product_Update_No")+1);
					rs.updateRow();
					}
		else{
			result=false;
		}
			 }catch(Exception e){
				 e.printStackTrace();
				 result=false;
			 }
			
			 CommonFunction.closeConn(null, pstm, stm, rs);
			 
		   return result;
	   }
	   
	 

}
